﻿using System;
using System.Data;
using System.IO;
using System.Collections.Generic;
using System.Web;

namespace SiteFox.Business.Logic
{
    public class FileManager
    {
        //===== Enum Statics =====//
        public enum ActionToDo { Copy, Move };
        public enum ObjectType { DirectoryInfo, FileInfo };
        //===== Read or Write =====//
        public static string ReadFileSource(string VirPath) 
        {
            StreamReader _StreamReader = new StreamReader(HttpContext.Current.Server.MapPath(VirPath));
            string _Source = _StreamReader.ReadToEnd();
            _StreamReader.Close();
            _StreamReader.Dispose();
            return _Source;
        }
        public static void WriteFileSource(string VirPath, string Source)
        {
            StreamWriter _StreamWriter = new StreamWriter(HttpContext.Current.Server.MapPath(VirPath));
            _StreamWriter.Write(Source);
            _StreamWriter.Flush();
            _StreamWriter.Close();
        }
        //===== Get =====//
        public static DataTable GetAllContent(string _VirPath) 
        {
            string _Path = HttpContext.Current.Server.MapPath(_VirPath);
            DataTable _Table = new DataTable();
            DataColumn _Column;
            DataRow _Row;
            //Table definition
            _Column = new DataColumn();
            _Column.DataType = Type.GetType("System.Int32");
            _Column.ColumnName = "Id";
            _Table.Columns.Add(_Column);

            _Column = new DataColumn();
            _Column.DataType = Type.GetType("System.String");
            _Column.ColumnName = "IconPath";
            _Table.Columns.Add(_Column);

            _Column = new DataColumn();
            _Column.DataType = Type.GetType("System.String");
            _Column.ColumnName = "Name";
            _Table.Columns.Add(_Column);

            _Column = new DataColumn();
            _Column.DataType = Type.GetType("System.String");
            _Column.ColumnName = "FullName";
            _Table.Columns.Add(_Column);

            _Column = new DataColumn();
            _Column.DataType = Type.GetType("System.String");
            _Column.ColumnName = "Extension";
            _Table.Columns.Add(_Column);

            _Column = new DataColumn();
            _Column.DataType = Type.GetType("System.String");
            _Column.ColumnName = "Type";
            _Table.Columns.Add(_Column);

            _Column = new DataColumn();
            _Column.DataType = Type.GetType("System.String");
            _Column.ColumnName = "Lenght";
            _Table.Columns.Add(_Column);

            _Column = new DataColumn();
            _Column.DataType = Type.GetType("System.Boolean");
            _Column.ColumnName = "ViewAsPage";
            _Table.Columns.Add(_Column);

            _Column = new DataColumn();
            _Column.DataType = Type.GetType("System.String");
            _Column.ColumnName = "ViewAsPagePath";
            _Table.Columns.Add(_Column);

            _Column = new DataColumn();
            _Column.DataType = Type.GetType("System.Boolean");
            _Column.ColumnName = "ViewAsCode";
            _Table.Columns.Add(_Column);

            _Column = new DataColumn();
            _Column.DataType = Type.GetType("System.String");
            _Column.ColumnName = "ViewAsCodePath";
            _Table.Columns.Add(_Column);

            //end of table definition
            //fill table with folders
            int _iRowCount = 1;
            if (!new FileInfo(_Path).Exists)
            {
                string[] _Folders = Directory.GetDirectories(_Path);
                for (int i = 0; i < _Folders.Length; i++)
                {
                    DirectoryInfo _Dir = new DirectoryInfo(_Folders[i]);
                    if (_Dir.Attributes == FileAttributes.Directory)
                    {
                        _Row = _Table.NewRow();
                        _Row["Id"] = _iRowCount;
                        _Row["IconPath"] = "~/System/Design/ico/Common/folder.gif";
                        _Row["Name"] = _Dir.Name;
                        _Row["FullName"] = _Dir.FullName;
                        _Row["Extension"] = "";
                        _Row["Type"] = ObjectType.DirectoryInfo.ToString();
                        _Row["Lenght"] = "";
                        _Row["ViewAsPage"] = false;
                        _Row["ViewAsPagePath"] = "";
                        _Row["ViewAsCode"] = false;
                        _Row["ViewAsCodePath"] = "";
                        _Table.Rows.Add(_Row);
                        _iRowCount++;
                    }
                }

                string[] _Files = Directory.GetFiles(_Path);
                for (int i = 0; i < _Files.Length; i++)
                {
                    FileInfo _File = new FileInfo(_Files[i]);
                    _Row = _Table.NewRow();
                    _Row["Id"] = _iRowCount;
                    _Row["Name"] = _File.Name;
                    _Row["FullName"] = _File.FullName;
                    _Row["Extension"] = _File.Extension.Substring(1);
                    _Row["Type"] = ObjectType.FileInfo.ToString();
                    _Row["Lenght"] = _File.Length.ToString("N0") + " b";
                    Model.Extension _Extension = SiteFox.Business.Manager.Extension.GetByExt(_File.Extension.Substring(1));
                    if (_Extension != null) 
                    {
                        _Row["IconPath"] = _Extension.SmallIconUrl;
                        bool _ViewAsPage = false;
                        string _ViewAsPagePath = "";
                        bool _ViewAsCode = false;
                        string _ViewAsCodePath = "";
                        string _AppPath = HttpContext.Current.Request.ApplicationPath;
                        if (_AppPath == "/") 
                        {
                            _AppPath = "";
                        }

                        if (_Extension.Ext == "master") 
                        {
                            _ViewAsCode = true;
                            _ViewAsCodePath = "window.open ('" + _AppPath + "/System/Controls/Common/CodeEditor.aspx?FilePath=" + _VirPath + "/" + _File.Name + "','CodeEditor','location=0,status=1,scrollbars=1,width=1200,height=750,toolbar=0,menubar=0,directories=0,resizable=0');";
                        }
                        else if (_Extension.Ext == "aspx") 
                        {
                            _ViewAsCode = true;
                            _ViewAsCodePath = "window.open ('" + _AppPath + "/System/Controls/Common/CodeEditor.aspx?FilePath=" + _VirPath + "/" + _File.Name + "','CodeEditor','location=0,status=1,scrollbars=1,width=1200,height=750,toolbar=0,menubar=0,directories=0,resizable=0');";
                            _ViewAsPage = true;
                            _ViewAsPagePath = _VirPath + "/" + _File.Name;
                        }
                        else if (_Extension.AllowCreate)
                        {
                            _ViewAsCode = true;
                            _ViewAsCodePath = "window.open ('" + _AppPath + "/System/Controls/Common/CodeEditor.aspx?FilePath=" + _VirPath + "/" + _File.Name + "','CodeEditor','location=0,status=1,scrollbars=1,width=1200,height=750,toolbar=0,menubar=0,directories=0,resizable=0');";
                        }
                        _Row["ViewAsPage"] = _ViewAsPage;
                        _Row["ViewAsPagePath"] = _ViewAsPagePath;
                        _Row["ViewAsCode"] = _ViewAsCode;
                        _Row["ViewAsCodePath"] = _ViewAsCodePath;
                        if (!_Extension.Hidden) 
                        { 
                            _Table.Rows.Add(_Row);
                            _iRowCount++;
                        }
                    }
                    
                }
            }
            return _Table;
        }
        public static ObjectType GetObjectType(string _Path) 
        {
            ObjectType _Type = ObjectType.DirectoryInfo;
            if (new DirectoryInfo(_Path).Exists) 
            {
                _Type = ObjectType.DirectoryInfo;
            }
            else if (new FileInfo(_Path).Exists) 
            {
                _Type = ObjectType.FileInfo;
            }
            return _Type;
        }
        public static string GetParentPath(string SourcePath) 
        {
            return "~" + SourcePath.Substring(1, SourcePath.LastIndexOf("/") - 1);
        }
        private static List<string> GetObjectsId(string ContentSource, string ObjectToFind) 
        {
            string _ContentSource = ContentSource.ToLower();
            string _ObjectToFind = ObjectToFind.ToLower();
            
            List<string> _ObjectsId = new List<string>();
            string[] _SeparatedSource = _ContentSource.Split(new string[] { _ObjectToFind }, StringSplitOptions.None);
            for (int i = 0; i < _SeparatedSource.Length; i++) 
            { 
                int _cph_Position = _ContentSource.IndexOf(_ObjectToFind);
                if (_cph_Position > 0) 
                {
                    _ContentSource = _ContentSource.Substring(_cph_Position + _ObjectToFind.Length);
                    int _cph_Id_Position = _ContentSource.IndexOf("id");
                    _ContentSource = _ContentSource.Substring(_cph_Id_Position);
                    int _cph_Value_Position = _ContentSource.IndexOf("\"") + 1;
                    _ContentSource = _ContentSource.Substring(_cph_Value_Position);
                    _ObjectsId.Add(_ContentSource.Substring(0, _ContentSource.IndexOf("\"")));
                }
            }
            return _ObjectsId;
        }
        //===== Create =====//
        public static void CreateNewFolder(string VirSourcePath, string FolderName, out string Message)
        {
            string _VirSourcePath = HttpContext.Current.Server.MapPath(VirSourcePath);
            string _Message = "";
            DirectoryInfo _Directory = new DirectoryInfo(_VirSourcePath);
            DirectoryInfo _DirectoryToCreate = new DirectoryInfo(_VirSourcePath + "\\" + FolderName);
            if (_Directory.Exists) 
            {
                if (_DirectoryToCreate.Exists)
                {
                    _Message = "Directory already exists";
                }
                else 
                {
                    _Directory.CreateSubdirectory(FolderName);
                    _Message = "Directory successfully created";
                }
            }
            Message = _Message;
        }
        public static void CreateNewTextFile(string TargetPath, string FileName, string FileExt, out string Message) 
        {
            string _Message = "";
            FileInfo _File = new FileInfo(HttpContext.Current.Server.MapPath(TargetPath) + "\\" + FileName + "." + FileExt);
            if (_File.Exists)
            {
                _Message = "File already exists";
            }
            else 
            {
                FileStream _FileStream = _File.Create();
                _FileStream.Close();
                _Message = "File successfully created";
            }
            Message = _Message;
        }
        public static void CreateNewFormAsMaster(string TargetPath, string FileName, string FileExt, bool UseMasterPage, bool UseWebPartZone, bool UseNavigation, string MasterPagePath, out string Message)
        {
            string _Message = "";
            FileInfo fi = new FileInfo(HttpContext.Current.Server.MapPath(TargetPath) + "\\" + FileName + "." + FileExt);
            if (fi.Exists)
            {
                _Message = "File already exists";
            }
            else
            {
                if (!UseMasterPage)
                {
                    StreamReader srTemplate = new StreamReader(HttpContext.Current.Server.MapPath("~/System/FormTemplates/master.txt"));
                    string TemplateSource = srTemplate.ReadToEnd();
                    if (UseWebPartZone)
                    {
                        TemplateSource = TemplateSource.Replace("[_WebPartZone]", "<asp:WebPartZone ID=\"wpz\" HeaderText=\"Main\" runat=\"server\"></asp:WebPartZone>");
                    }
                    else 
                    {
                        TemplateSource = TemplateSource.Replace("[_WebPartZone]", "");
                    }
                    if (UseNavigation)
                    {
                        TemplateSource = TemplateSource.Replace("[_RegisterNavigation]", "<%@ Register Assembly=\"SiteFox.WebParts\" Namespace=\"SiteFox.WebParts.Navigation\" TagPrefix=\"uccwpNavigation\" %>");
                        TemplateSource = TemplateSource.Replace("[_Navigation]", "<uccwpNavigation:MenuWP ID=\"TopNavWP\" runat=\"server\" MaximumDynamicDisplayLevels=\"5\" Orientation=\"Horizontal\" CssClass=\"custom_TopNavWP\" />");
                    }
                    else 
                    {
                        TemplateSource = TemplateSource.Replace("[_RegisterNavigation]", "");
                        TemplateSource = TemplateSource.Replace("[_Navigation]", "");
                    }
                    TemplateSource = TemplateSource.Replace("[_RegisterCatalogZone]", "<%@ Register Src=\"~/System/Controls/Common/CatalogZone.ascx\" TagName=\"CatalogZone\" TagPrefix=\"ucc\" %>");
                    TemplateSource = TemplateSource.Replace("[_CatalogZone]", "<ucc:CatalogZone ID=\"CatalogZone\" runat=\"server\" />");

                    TemplateSource = TemplateSource.Replace("[_RegisterEditorZone]", "<%@ Register Src=\"~/System/Controls/Common/EditorZone.ascx\" TagName=\"EditorZone\" TagPrefix=\"ucc\" %>");
                    TemplateSource = TemplateSource.Replace("[_EditorZone]", "<ucc:EditorZone ID=\"EditorZone\" runat=\"server\" />");

                    TemplateSource = TemplateSource.Replace("[_RegisterEditorBar]", "<%@ Register Src=\"~/System/Controls/Common/EditorBar.ascx\" TagName=\"EditorBar\" TagPrefix=\"ucc\" %>");
                    TemplateSource = TemplateSource.Replace("[_EditorBar]", "<ucc:EditorBar ID=\"EditorBar\" runat=\"server\" />");

                    TemplateSource = TemplateSource.Replace("[_RegisterMetaTag]", "<%@ Register Src=\"~/System/Controls/Common/MetaTag.ascx\" TagName=\"MetaTag\" TagPrefix=\"ucc\" %>");
                    TemplateSource = TemplateSource.Replace("[_MetaTag]", "<ucc:MetaTag ID=\"MetaTag\" runat=\"server\" />");

                    FileStream fs = fi.Create();
                    fs.Close();
                    StreamWriter sw = new StreamWriter(fi.FullName);
                    sw.Write(TemplateSource);
                    sw.Flush();
                    sw.Close();
                    _Message = "MasterPage successfully created";
                }
                else
                {
                    StreamReader srTemplate = new StreamReader(HttpContext.Current.Server.MapPath("~/System/FormTemplates/master_WithMaster.txt"));
                    string TemplateSource = srTemplate.ReadToEnd();

                    StreamReader srMaster = new StreamReader(HttpContext.Current.Server.MapPath(MasterPagePath));
                    string MasterSource = srMaster.ReadToEnd();

                    List<string> _ObjectsId = GetObjectsId(MasterSource, "<asp:ContentPlaceHolder");
                    string _Content = "";
                    for (int i = 0; i < _ObjectsId.Count; i++)
                    {
                        _Content += "<asp:Content ID=\"c_" + _ObjectsId[i] + "\" ContentPlaceHolderID=\"" + _ObjectsId[i] + "\" Runat=\"Server\">\r\n</asp:Content>\r\n";
                    }
                    TemplateSource = TemplateSource.Replace("[_MasterPagePath]", MasterPagePath);
                    TemplateSource = TemplateSource.Replace("[_Content]", _Content);
                    TemplateSource = TemplateSource.Replace("[_RegisterEditorBar]", "");
                    TemplateSource = TemplateSource.Replace("[_EditorBar]", "");

                    FileStream fs = fi.Create();
                    fs.Close();
                    StreamWriter sw = new StreamWriter(fi.FullName);
                    sw.Write(TemplateSource);
                    sw.Flush();
                    sw.Close();
                    _Message = "MasterPage successfully created";
                }
            }
            Message = _Message;
        }
        public static void CreateNewFormAsPage(string TargetPath, string FileName, string FileExt, string PageTitle, bool UseMasterPage, string MasterPagePath, out string Message)
        {
            string _Message = "";
            FileInfo fi = new FileInfo(HttpContext.Current.Server.MapPath(TargetPath) + "\\" + FileName + "." + FileExt);
            if (fi.Exists)
            {
                _Message = "File already exists";
            }
            else
            {
                if (!UseMasterPage)
                {
                    StreamReader srTemplate = new StreamReader(HttpContext.Current.Server.MapPath("~/System/FormTemplates/aspx.txt"));
                    string TemplateSource = srTemplate.ReadToEnd();

                    TemplateSource = TemplateSource.Replace("[_PageTitle]", PageTitle);

                    FileStream fs = fi.Create();
                    fs.Close();
                    StreamWriter sw = new StreamWriter(fi.FullName);
                    sw.Write(TemplateSource);
                    sw.Flush();
                    sw.Close();
                    _Message = "Page successfully created";
                }
                else
                {
                    StreamReader srTemplate = new StreamReader(HttpContext.Current.Server.MapPath("~/System/FormTemplates/aspx_WithMaster.txt"));
                    string TemplateSource = srTemplate.ReadToEnd();

                    StreamReader srMaster = new StreamReader(HttpContext.Current.Server.MapPath(MasterPagePath));
                    string MasterSource = srMaster.ReadToEnd();

                    List<string> _ObjectsId = GetObjectsId(MasterSource, "<asp:ContentPlaceHolder");
                    string _Content = "";
                    for (int i = 0; i < _ObjectsId.Count; i++) 
                    {
                        _Content += "<asp:Content ID=\"Content_" + _ObjectsId[i] + "\" ContentPlaceHolderID=\"" + _ObjectsId[i] + "\" Runat=\"Server\">\r\n</asp:Content>\r\n";
                    }
                    TemplateSource = TemplateSource.Replace("[_PageTitle]", PageTitle);
                    TemplateSource = TemplateSource.Replace("[_MasterPagePath]", MasterPagePath);
                    TemplateSource = TemplateSource.Replace("[_Content]", _Content);

                    FileStream fs = fi.Create();
                    fs.Close();
                    StreamWriter sw = new StreamWriter(fi.FullName);
                    sw.Write(TemplateSource);
                    sw.Flush();
                    sw.Close();
                    _Message = "Page successfully created";
                }
            }
            Message = _Message;
        }
        //===== Copy or Move =====//
        public static void CopyOrMove(DataTable Objects, ActionToDo Action, string SourcePath, string TargetPath, bool OverwriteObjects, out DataTable ActionLog, out double ActionDone) 
        {
            string _SourcePath = HttpContext.Current.Server.MapPath(SourcePath);
            string _TargetPath = HttpContext.Current.Server.MapPath(TargetPath);
            
            int _ActionNumber = Objects.Rows.Count;
            int _ActionCompleted = 0;
            
            DataTable CopyLogTable = new DataTable();
            DataColumn CopyLogColumn;
            DataRow CopyLogRow;

            CopyLogColumn = new DataColumn();
            CopyLogColumn.DataType = Type.GetType("System.Boolean");
            CopyLogColumn.ColumnName = "Status";
            CopyLogTable.Columns.Add(CopyLogColumn);

            CopyLogColumn = new DataColumn();
            CopyLogColumn.DataType = Type.GetType("System.String");
            CopyLogColumn.ColumnName = "FileName";
            CopyLogTable.Columns.Add(CopyLogColumn);

            CopyLogColumn = new DataColumn();
            CopyLogColumn.DataType = Type.GetType("System.String");
            CopyLogColumn.ColumnName = "Message";
            CopyLogTable.Columns.Add(CopyLogColumn);
            
            for (int i = 0; i < _ActionNumber; i++) 
            {
                bool myObjectStatus = false;
                string myObjectMessage = "";
                DataRow myObject = Objects.Rows[i];
                if (myObject.ItemArray[1].ToString() == ObjectType.DirectoryInfo.ToString()) 
                {
                    DirectoryInfo diSource = new DirectoryInfo(_SourcePath + "\\" + myObject.ItemArray[0].ToString());
                    DirectoryInfo diTarget = new DirectoryInfo(_TargetPath + "\\" + myObject.ItemArray[0].ToString());
                    if (diTarget.Exists == true)
                    {
                        if (OverwriteObjects)
                        {
                            diTarget.Delete(true);
                            if (Action == ActionToDo.Copy) 
                            { 
                                CopyFolderWithContent(diSource, diTarget);
                            }
                            else if (Action == ActionToDo.Move) 
                            {
                                MoveFolderWithContent(diSource, diTarget);
                            }
                            myObjectMessage = "Directory successfully overwrited";
                            myObjectStatus = true;
                            _ActionCompleted++;
                        }
                        else
                        {
                            myObjectMessage = "Directory already exists";
                            myObjectStatus = false;
                        }
                    }
                    else
                    {
                        if (Action == ActionToDo.Copy)
                        {
                            CopyFolderWithContent(diSource, diTarget);
                            myObjectMessage = "Directory successfully copied";
                        }
                        else if (Action == ActionToDo.Move)
                        {
                            MoveFolderWithContent(diSource, diTarget);
                            myObjectMessage = "Directory successfully moved";
                        }
                        myObjectStatus = true;
                        _ActionCompleted++;
                    }
                }
                else if (myObject.ItemArray[1].ToString() == ObjectType.FileInfo.ToString()) 
                {
                    FileInfo fiSource = new FileInfo(_SourcePath + "\\" + myObject.ItemArray[0].ToString());
                    FileInfo fiTarget = new FileInfo(_TargetPath + "\\" + myObject.ItemArray[0].ToString());

                    if (fiTarget.Exists)
                    {
                        if (OverwriteObjects)
                        {
                            if (Action == ActionToDo.Copy) 
                            { 
                                fiSource.CopyTo(fiTarget.FullName, OverwriteObjects);
                            }
                            else if (Action == ActionToDo.Move) 
                            {
                                fiTarget.Delete();
                                fiSource.MoveTo(fiTarget.FullName);
                            }
                            myObjectMessage = "File successfully overwrited";
                            myObjectStatus = true;
                            _ActionCompleted++;
                        }
                        else
                        {
                            myObjectMessage = "File already exists";
                            myObjectStatus = false;
                        }
                    }
                    else 
                    {
                        if (Action == ActionToDo.Copy)
                        {
                            fiSource.CopyTo(fiTarget.FullName, OverwriteObjects);
                            myObjectMessage = "File successfully copied";
                        }
                        else if (Action == ActionToDo.Move)
                        {
                            fiSource.MoveTo(fiTarget.FullName);
                            myObjectMessage = "File successfully moved";
                        }
                        myObjectStatus = true;
                        _ActionCompleted++;
                    }
                }
                CopyLogRow = CopyLogTable.NewRow();
                CopyLogRow["Status"] = myObjectStatus;
                CopyLogRow["FileName"] = myObject.ItemArray[0].ToString();
                CopyLogRow["Message"] = myObjectMessage;
                CopyLogTable.Rows.Add(CopyLogRow);
            }
            ActionDone = (Convert.ToDouble(100) / Convert.ToDouble(_ActionNumber)) * Convert.ToDouble(_ActionCompleted);
            ActionLog = CopyLogTable;
        }
        public static void CopyFolderWithContent(DirectoryInfo _DirectorySource, DirectoryInfo _DirectoryTarget)
        {
            int iterator = 0;
            List<DirectoryInfo> _DirectorySourceList = new List<DirectoryInfo>();
            List<FileInfo> _FileSourceList = new List<FileInfo>();

            _DirectorySourceList.Add(_DirectorySource);

            while (iterator < _DirectorySourceList.Count)
            {
                foreach (DirectoryInfo _Directory in _DirectorySourceList[iterator].GetDirectories())
                {
                    _DirectorySourceList.Add(_Directory);
                }
                foreach (FileInfo _File in _DirectorySourceList[iterator].GetFiles())
                {
                    _FileSourceList.Add(_File);
                }
                iterator++;
            }

            foreach (DirectoryInfo _Directory in _DirectorySourceList)
            {
                if (_Directory.Exists)
                {
                    string sFolderPath = _DirectoryTarget.FullName + @"\" + _Directory.FullName.Remove(0, _DirectorySource.FullName.Length);

                    ///// Prevent Silly IOException /////
                    if (!Directory.Exists(sFolderPath))
                    {
                        Directory.CreateDirectory(sFolderPath);
                    }

                }
            }

            foreach (FileInfo _File in _FileSourceList)
            {
                if (_File.Exists)
                {
                    string sFilePath = _DirectoryTarget.FullName + @"\" + _File.FullName.Remove(0, _DirectorySource.FullName.Length);

                    _File.CopyTo(sFilePath, true);
                }
            }
        }
        public static void MoveFolderWithContent(DirectoryInfo _DirectorySource, DirectoryInfo _DirectoryTarget)
        {
            if (_DirectoryTarget.Exists == false) 
            {
                _DirectorySource.MoveTo(_DirectoryTarget.FullName);
            }
        }
        //===== Delete =====//
        public static void Delete(DataTable Objects, string SourcePath) 
        {
            string _SourcePath = HttpContext.Current.Server.MapPath(SourcePath);
            for (int i = 0; i < Objects.Rows.Count; i++)
            {
                DataRow myObject = Objects.Rows[i];
                if (myObject.ItemArray[1].ToString() == ObjectType.DirectoryInfo.ToString())
                { 
                    DirectoryInfo dirSource = new DirectoryInfo(_SourcePath + "\\" + myObject.ItemArray[0].ToString());
                    int iterator = 0;
                    List<DirectoryInfo> diSourceList = new List<DirectoryInfo>();
                    List<FileInfo> fiSourceList = new List<FileInfo>();

                    diSourceList.Add(dirSource);

                    while (iterator < diSourceList.Count)
                    {
                        foreach (DirectoryInfo di in diSourceList[iterator].GetDirectories())
                        {
                            diSourceList.Add(di);
                        }
                        foreach (FileInfo fi in diSourceList[iterator].GetFiles())
                        {
                            fiSourceList.Add(fi);
                        }
                        iterator++;
                    }

                    for (int iFile = 0; iFile < fiSourceList.Count; iFile++)
                    {
                        FileInfo fi = fiSourceList[fiSourceList.Count - iFile - 1];
                        if (fi.Exists)
                        {
                            fi.Delete();
                        }
                    }

                    for (int iDir = 0; iDir < diSourceList.Count; iDir++)
                    {
                        DirectoryInfo di = diSourceList[diSourceList.Count - iDir - 1];
                        if (di.Exists)
                        {
                            try { di.Delete(true); }
                            catch { }
                            try { di.Delete(); }
                            catch { }
                        }
                    }
                }
                else if (myObject.ItemArray[1].ToString() == ObjectType.FileInfo.ToString()) 
                {
                    FileInfo fi = new FileInfo(_SourcePath + "\\" + myObject.ItemArray[0].ToString());
                    fi.Delete();
                }
            }
        }
    }
}
